<template>
  <div class="app-container image">
    <div class="image-header">
      <el-button type="primary" size="mini" @click="dialog.createSource = true">新建隔离资源</el-button>
    </div>
    <el-table
      :data="list"
      style="width: 100%">
      <el-table-column
        label="节点ID">
        <template slot-scope="scope">
          <div>
            <span>{{ scope.row.node_id }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        prop="name"
        label="已隔离GPU">
        <template slot-scope="scope">
          <span>{{ scope.row.unhealthy_gpu }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" align="center">
        <template slot-scope="scope">
          <a class="table-action" @click="clickCheckLog(scope.row)">日志</a>
          <a class="table-action" @click="clickUpdateSource(scope.row)">编辑</a>
          <a class="table-action" @click="clickDeleteSource(scope.row)">删除</a>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog
      :visible.sync="dialog.createSource"
      :title="dialog.editSource ? '编辑隔离' : '新建隔离'"
      width="600px"
      @close="resetForm('createSourceForm')">
      <el-form ref="createSourceForm" :model="createSourceForm" :rules="rulesCreateSource" label-width="150px">
        <el-form-item label="ID：" prop="id">
          <el-input :disabled="dialog.editSource" v-model="createSourceForm.id" />
        </el-form-item>
        <el-form-item label="已隔离的GPU：" prop="gpu">
          <el-input v-model="createSourceForm.gpu" />
        </el-form-item>
        <el-form-item label="备注：" prop="remark">
          <el-input v-model="createSourceForm.remark" :rows="3" type="textarea" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialog.createSource = false; dialog.editSource = false;">取 消</el-button>
        <el-button type="primary" @click="submitForm('createSourceForm')">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { handleUnavailable } from '@/api/source'

export default {
  data() {
    return {
      list: null,
      listLoading: true,
      selCluster: '',
      clusterOptions: [],
      dialog: {
        createSource: false,
        editSource: false
      },
      createSourceForm: {
        id: '',
        gpu: '',
        remark: ''
      },
      rulesCreateSource: {
        id: [
          { required: true, message: '请输入ID', trigger: 'blur' }
        ],
        gpu: [
          { required: true, message: '请输入已隔离GPU', trigger: 'blur' }
        ],
        remark: [
          { required: true, message: '请输入备注', trigger: 'blur' }
        ]
      },
      curEditRow: ''
    }
  },
  computed: {
    ...mapGetters([
      'userName'
    ])
  },
  created() {
    this._handleUnavaliable('Get')
  },
  methods: {
    // 点击table名称
    toDetail(row) {
      this.$store.dispatch('SaveCurCLuster', row)
      this.$router.push({ path: '/cluster/nodes' })
    },
    // 点击查看日志
    clickCheckLog(row) {
      const item = row
      item.clcuster = this.selCluster
      this.$store.dispatch('SaveCurSourceCluster', item)
      this.$router.push({ path: '/source/logs' })
    },
    // 点击删除资源
    clickDeleteSource(row) {
      this.$confirm(`此操作将删除该隔离资源${row.node_id}, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const data = {
          node_id: row.node_id
        }
        this._handleUnavaliable('Delete', data)
      })
    },
    // 编辑资源
    clickUpdateSource(row) {
      this.dialog.editSource = true
      this.dialog.createSource = true
      this.curEditRow = row
      this.createSourceForm = {
        id: row.node_id,
        gpu: row.unhealthy_gpu
      }
    },
    // 重置表单
    resetForm(formName) {
      this.dialog.editSource = false
      this.createSourceForm = {
        id: '',
        gpu: ''
      }
      this.$refs[formName].resetFields()
    },
    // 表单提交(createSourceForm: 新建镜像)
    submitForm() {
      const method = this.dialog.editSource ? 'Put' : 'Post'
      this.$refs['createSourceForm'].validate((valid) => {
        if (valid) {
          const data = {
            node_id: this.createSourceForm.id,
            unhealthy_gpu: this.convertNumber(this.createSourceForm.gpu),
            remark: this.createSourceForm.remark
          }
          this._handleUnavaliable(method, data)
          this.dialog.createSource = false
          this.resetForm('createSourceForm')
        } else {
          return false
        }
      })
    },
    // 二进制转换
    convertBinary(val) {
      let gpuStr = ''
      const binay = val.toString(2)
      for (let i = 0; i < binay.length; i++) {
        if ((1 << i) & val) {
          gpuStr += i.toString()
        }
      }
      return gpuStr
    },
    // 二进制转换
    convertNumber(val) {
      let result = 0
      for (let i = 0; i < val.length; i++) {
        result |= (1 << Number(val[i]))
      }
      return result
    },
    // 隔离资源操作（查询列表：Get,新增：Post,修改：Put,删除：Delete）
    _handleUnavaliable(method, data) {
      this.listLoading = true
      handleUnavailable(method, data).then(res => {
        if (res.message.code === 0) {
          this.listLoading = false
          switch (method) {
            case 'Get':
              this.list = res.data
              this.list.map(item => {
                item.unhealthy_gpu = this.convertBinary(item.unhealthy_gpu)
              })
              break
            case 'Post':
              this.$message({ message: '新建成功', showClose: true, type: 'success' })
              this._handleUnavaliable('Get')
              break
            case 'Put':
              this.$message({ message: '修改成功', showClose: true, type: 'success' })
              this._handleUnavaliable('Get')
              break
            case 'Delete':
              this.$message({ message: '删除成功', showClose: true, type: 'success' })
              this._handleUnavaliable('Get')
              break
          }
        } else {
          this.$message({ message: res.message.message, showClose: true, type: 'error' })
        }
      })
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.image {
  &-header {
    padding: 10px;
    background: #ffffff;
    font-size: 14px;
    color: #303133;
    font-weight: bold;
    .header-title {
      font-size: 14px;
      font-weight: 700;
    }
    .header-title-left {
      float: right;
      height: 40px;
      line-height: 40px;
    }
  }
  label {
    font-weight: normal
  }
  .table-action {
    color: #4285f4;
    margin: 0 2px;
  }
  .table-link {
    color: #4285f4;
    &:hover {
      cursor: pointer;
    }
  }
  .status-box {
    border-radius: 5px;
    padding: 0 5px;
    color: #000000;
  }
  .status-success {
    background: #63D4AD;
  }
  .status-run {
    background: #85D8F7;
  }
  .status-wait {
    background: #f39c12;
  }
  .status-stop {
    background: #E0E3E8;
  }
  .status-failure {
    background: #F87D8D
  }
}
</style>
